package com.idp.web.controller;

import com.idp.common.base.BaseController;
import com.idp.common.base.BaseResult;
import com.idp.common.constants.CommonConstants;
import com.idp.common.constants.Constants;
import com.idp.common.model.UploadModel;
import com.idp.common.persistence.Page;
import com.idp.common.util.UploadUtils;
import com.idp.common.util.ValidateUtils;
import com.idp.web.dto.DepartmentSelectListDTO;
import com.idp.web.dto.HospitalListDTO;
import com.idp.web.entity.Hospitals;
import com.idp.web.service.IDepartmentService;
import com.idp.web.service.IHospitalsService;
import com.idp.web.vo.HospitalsSearchVo;
import net.sf.json.JSONObject;
import org.apache.commons.lang.StringUtils;
import org.apache.ibatis.annotations.Param;
import org.apache.log4j.Logger;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.List;

/**
 * 医院controller
 *
 * @author xubinren
 * @version 1.0
 * @date 2018/2/27
 */
@Controller
@RequestMapping("/hospitals")
public class HospitalsController extends BaseController {

    private Logger logger = Logger.getLogger(HospitalsController.class);

    @Resource
    private IHospitalsService hospitalsService;

    @Resource
    private IDepartmentService departmentService;

    /**
     * 初始化查询页面
     *
     * @return String
     */
    @RequestMapping("/init")
    public String init() {
        return "backstage/hospital/hospitalsSearch";
    }

    /**
     * 根据条件分页查询医院列表
     *
     * @param hospitalsSearch 医院信息
     * @param page            分页信息
     * @param request
     * @return String
     */
    @RequestMapping("/list")
    public String list(HospitalsSearchVo hospitalsSearch, Page<HospitalListDTO> page, HttpServletRequest request) {
        try {
            request.setAttribute("page", hospitalsService.findByPage(hospitalsSearch, page));
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
        }
        return "backstage/hospital/hospitalsList";
    }

    /**
     * 新增修改页面初始化
     *
     * @param id      医院id
     * @param request
     * @return String
     */
    @RequestMapping("/hospitals")
    public String hospitals(String id, HttpServletRequest request) {

        try {
            if (ValidateUtils.isNotEmpty(id)) {
                Hospitals hospitals = hospitalsService.getById(id);
                request.setAttribute("hospitals", hospitals);
            }
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
        }
        return "backstage/hospital/hospitals";
    }

    /**
     * 查看页面初始化
     *
     * @param id      医院id
     * @param request
     * @return String
     */
    @RequestMapping("/show")
    public String show(String id, HttpServletRequest request) {

        try {
            if (ValidateUtils.isNotEmpty(id)) {
                Hospitals hospitals = hospitalsService.getById(id);
                request.setAttribute("hospitals", hospitals);
            } else {
                logger.info("参数错误");
            }
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
        }
        return "backstage/hospital/hospitalsShow";
    }

    /**
     * 保存
     *
     * @return
     */
    @RequestMapping("/save")
    @ResponseBody
    public String save(HttpServletRequest request) {

        JSONObject json = new JSONObject();
        try {
            Hospitals hospitals = new Hospitals();
            UploadModel model = new UploadModel(UploadUtils.getServerUploadBasePath(UploadUtils.PATH_IMAGES),
                    UploadModel.IMAGES, hospitals);
            UploadUtils.uploadFileSealedObject(request, model);

            if (ValidateUtils.isNotEmpty(hospitals.getId())) {
                // 修改
                hospitalsService.update(hospitals, getUserId());
            } else {
                // 新增
                hospitalsService.add(hospitals, getUserId());
            }
            json.put("result", "save_success");
        } catch (Exception e) {

            logger.error(e.getMessage(), e);
            json.put("result", "save_fail");
        }
        return json.toString();
    }

    /**
     * 删除
     *
     * @param id 医院id
     * @return String
     */
    @RequestMapping("/delete")
    @ResponseBody
    public String delete(String id) {
        JSONObject json = new JSONObject();
        try {
            hospitalsService.delete(id);
            json.put("result", "delete_success");
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
            json.put("result", "delete_fail");
        }
        return json.toString();
    }

    /**
     * 根据医院名称查询对应的医院信息：精确查询
     *
     * @param hospitalName 医院名称
     * @return BaseResult
     */
    @RequestMapping("/getByName")
    @ResponseBody
    public BaseResult getByName(@Param(value = "hospitalName") String hospitalName) {
        if (StringUtils.isEmpty(hospitalName)) {
            return sendResult400();
        }
        Hospitals hospitals = hospitalsService.getByName(hospitalName);
        if (null == hospitals) {
            return sendResult(Constants.RESPONSE_CODE_602, Constants.RESPONSE_MESSAGE_602);
        }
        return sendResult200(hospitals);
    }

    /**
     * 添加编辑医院的科室页面初始化
     *
     * @param request HttpServletRequest
     * @return String
     */
    @RequestMapping("/hospitalsDepartment")
    public String hospitalsDepartment(HttpServletRequest request) {
        String hospitalId = CommonConstants.STRING_BLANK;
        if (CommonConstants.USER_TYPE_HOSPITAL == getUserType()){
            hospitalId = getUserId();
        }
        List<DepartmentSelectListDTO> listWeightOne = departmentService.selectListByWeight(CommonConstants.DEPARTMENT_WEIGHT_ONE,hospitalId);
        List<DepartmentSelectListDTO> listWeightTwo = departmentService.selectListByWeight(CommonConstants.DEPARTMENT_WEIGHT_TWO,hospitalId);
        request.setAttribute("listWeightOne", listWeightOne);
        request.setAttribute("listWeightTwo", listWeightTwo);
        return "backstage/hospital/hospitalsDepartment";
    }

    /**
     * 添加编辑医院的科室
     *
     * @param id      医院id
     * @param weightOneIds      一级科室id集合，以逗号隔开
     * @param weightTwoIds      二级科室id集合，以逗号隔开
     * @param request HttpServletRequest
     * @return String
     */
    @RequestMapping("/saveHospitalDepartment")
    @ResponseBody
    public String saveHospitalDepartment(
            String id, String weightOneIds, String weightTwoIds,
            HttpServletRequest request
    ) {
        JSONObject json = new JSONObject();
        try {
            if (ValidateUtils.isNotEmpty(id)
                    && ValidateUtils.isNotEmpty(weightOneIds)
                    && ValidateUtils.isNotEmpty(weightTwoIds)
                    ) {

            }
            json.put("result", "delete_success");
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
            json.put("result", "delete_fail");
        }
        return json.toString();
    }
}
